<template>
  <view class="input-search">
    <view
      class="is-border custom-comp"
      :class="[getDisabled && 'is-disabled']"
      @click="handleSearchPopup"
    >
      <PickerValue
        v-if="!getDisabled || elVal"
        :placeholder="getPlaceholder"
        :value-text="elVal"
        :disabled="getDisabled"
        style="flex: 1"
        :icon-style="{
          color: 'rgb(192, 196, 204)',
          fontSize: '40rpx',
        }"
        :icon="elVal && !getDisabled ? '\ue724' : '\ue694'"
        @icon-click="handleClear"
      />
      <!-- <UniEasyinput
        :placeholder="getDisabled ? '' : '请输入搜索关键字'"
        :value="elVal"
        type="text"
        trim
        inputBorder
        clearable
        disabled
        :styles="{
          color: '#333',
          backgroundColor: 'transparent',
          disableColor: 'transparent !important',
          borderColor: '#e5e5e5',
        }"
        suffixIcon="search"
      /> -->
    </view>
    <UniPopup ref="searchPopup" type="bottom" backgroundColor="#FFF" @change="onSearchPopup">
      <view class="search-popup">
        <view class="fontTC pt-22 fz-18 fw-7 mb-22">搜索</view>
        <UniEasyinput
          @input="onInput"
          :placeholder="getDisabled ? '' : getPlaceholder"
          v-model="searchInputVal"
          type="text"
          :disabled="false"
          trim
          inputBorder
          :focus="isFocus"
          adjust-position
          :suffixIcon="searchInputVal ? 'clear' : 'search'"
          confirm-type="search"
          @iconClick="handleClear"
        />
        <scroll-view scroll-y class="result-list">
          <Loading v-model="loading">
            <view style="min-height: 30vh">
              <template v-for="v in resultList" :key="v.id">
                <view class="result-item text-overflow-1" @click="clickResultItem(v)">
                  {{ v.name }}
                </view>
              </template>
              <Empty v-if="!resultList.length" />
            </view>
          </Loading>
        </scroll-view>
      </view>
    </UniPopup>
  </view>
</template>

<script setup lang="ts">
  import { computed, type PropType, ref, watchEffect, getCurrentInstance } from 'vue';
  import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import PickerValue from './PickerValue.vue';
  import Empty from '@/components/Empty/Empty.vue';
  import { getCollegesList, getMajorsList, getSchoolList, tianyanchaSearch } from '@/api';
  import { type TianyanchaSearchResult } from '@/api/indexTypes';
  import Loading from '@/components/Loading/index.vue';
  import { useFormItem } from '../hooks/useContext';
  import { propTypes } from '@/utils/propTypes';
  import { useDebounceFn } from '@vueuse/core';
  import { IsInternalInterfaceEnum } from '@/enums/formEnum';
  import { Toast } from '@/utils';
  import { isJSON } from '@/utils/is';
  import { isArray } from '@/utils/is';

  type Item = { id: number; name: string };

  const props = defineProps({
    modelValue: Object as PropType<Item>,
    disabled: propTypes.bool.def(false),
    placeholder: propTypes.string.def('请输入搜索关键字'),
    isInternalInterface: Number as PropType<IsInternalInterfaceEnum>,
  });

  const elVal = ref('');
  const loading = ref(true);
  const isFocus = ref(false);

  const resultList = ref<TianyanchaSearchResult[]>([]);

  const getPlaceholder = computed(() => {
    return getProps.value.placeholder || props.placeholder;
  });

  const { getProps, setFormModel } = useFormItem({});

  const getDisabled = computed(() => {
    return getProps.value.disabled || props.disabled;
  });

  watchEffect(() => {
    let modelValue = props.modelValue || getProps.value.modelValue;

    if (isArray(modelValue)) modelValue = modelValue[0];

    const val = isJSON(modelValue) || { name: modelValue };
    elVal.value = val.name;
  });

  const getIsInternalInterface = computed(
    () => getProps.value.isInternalInterface || props.isInternalInterface,
  );

  const getApi = computed((): null | ((keyword: string) => Promise<any>) => {
    const type = getIsInternalInterface.value;

    switch (type) {
      case IsInternalInterfaceEnum.TIANYANCHA:
        return tianyanchaSearch;
      case IsInternalInterfaceEnum.SCHOOL:
        return getSchoolList;
      case IsInternalInterfaceEnum.COLLEGE:
        return getCollegesList;
      case IsInternalInterfaceEnum.MAJOR:
        return getMajorsList;
      default:
        return null;
    }
  });

  const _this = getCurrentInstance();
  function handleSearchPopup() {
    if (getDisabled.value) return;
    searchInputVal.value = elVal.value;
    loading.value = false;
    search();
    (_this?.refs['searchPopup'] as any).open();
  }

  function onSearchPopup(e: { show: boolean }) {
    isFocus.value = e.show;
  }

  const searchInputVal = ref('');
  function search() {
    const api = getApi.value;
    if (!api) return Toast('未绑定数据源', 'error');
    const keyword = searchInputVal.value;
    loading.value = true;
    api(keyword)
      .then((r) => (resultList.value = r.records))
      .finally(() => (loading.value = false));
  }

  const onInput = useDebounceFn((value: string) => {
    search();
  }, 300);

  function clickResultItem(item: { id: number; name: string }) {
    searchInputVal.value = item.name;
    if (getIsInternalInterface.value === IsInternalInterfaceEnum.TIANYANCHA) {
      setFormModel(item, false);
    } else {
      setFormModel([JSON.stringify(item)], true);
    }
    (_this?.refs['searchPopup'] as any).close();
  }

  function handleClear() {
    if ((elVal.value || searchInputVal.value) && !getDisabled.value) {
      elVal.value = '';
      searchInputVal.value = '';
      resultList.value = [];
      setFormModel('');
    }
  }
</script>

<style scoped lang="scss">
  @import '../styles/form.scss';
  .input-search {
    position: relative;
    .search-popup {
      width: 100%;
      flex: 1;
      box-sizing: border-box;
      padding: 0 30rpx;
    }
    .result-list {
      position: relative;
      height: 40vh;
      padding: 20rpx 0;
      padding: 8rpx 0;
      .result-item {
        display: flex;
        cursor: pointer;
        line-height: 70rpx;
        font-size: 28rpx;
        padding: 0 20rpx;
      }
    }
  }
</style>
